#include "LPC11xx.h"
#include "timer32.h"
#include "uart.h"
#include "gpio.h"

/***************************************************************
 * Macro definitions                                           *
 ***************************************************************/

/***************************************************************
 * Globol variables                                            *
 ***************************************************************/
extern volatile uint32_t UARTCount;
extern volatile uint8_t UARTBuffer[BUFSIZE];

/***************************************************************
 * Functions                                                   *
 ***************************************************************/
void myDelay (uint32_t ulTime)
{
    uint32_t i;

    i = 0;
    while (ulTime--) {
        for (i = 0; i < 5000; i++);
    }
}

/***************************************************************
 * MAIN                                                        *
 ***************************************************************/
int main (void)
{
    uint32_t const UART_SEND_LEN = 12;
    uint8_t UARTStr[UART_SEND_LEN] = "Waiting...\r\n";


    SystemInit();             /* MUST BE INCLUDED! */

    GPIOInit();
    // LED
    GPIOSetDir(2, 7, GPIO_DIR_OUTPUT);

//    /* Set port 3.0 to down-edge interrupt. Last parament is useless. */
//    GPIOSetInterrupt(PORT3, 0, 0, 0, 0);
//    GPIOIntEnable(PORT3, 0);
//    GPIOSetIntCallback(3, myGPIOIntFunc);

//    /* Set a timer to call interrupt per second. */
//    Timer32Init(TIMER32_0, 3000 * (SystemAHBFrequency / 1000));
//    Timer32SetIntCallback(TIMER32_0, myTimerIntFunc);
//    Timer32Enable(TIMER32_0);

    /* Uart test */
    UARTInit(600);
//    myDelay(10);
//    UARTSend(UARTStr, UART_SEND_LEN);     // send message.


    while (1) {
        if ( UARTCount != 0 )
        {
            LPC_UART->IER = IER_THRE | IER_RLS;			/* Disable RBR */
            UARTSend( (uint8_t *)UARTBuffer, UARTCount );
            UARTCount = 0;
            LPC_UART->IER = IER_THRE | IER_RLS | IER_RBR;	/* Re-enable RBR */
        }
		else {
	        UARTSend(UARTStr, UART_SEND_LEN);     // send message.
			myDelay(100/LPC_SYSCON->SYSAHBCLKDIV);
            // blinky LED.
            GPIOSetValue(2, 7, !GPIOGetValue(2, 7));
		}
    }
}

/***************************************************************
 * END OF FILE                                                 *
 ***************************************************************/
